package com.witframework.web.file;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class FileDownloadServlet extends HttpServlet {

	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		try {
			ObjectInputStream oin = new ObjectInputStream(request.getInputStream());
			oin.readObject();
			// 保存写到浏览器的数据			
			String mimeType = request.getParameter("mimeType");
			String fileName = request.getParameter("fileName");
			String charset = request.getParameter("charset");
			if (null == charset) {
				charset = request.getCharacterEncoding();
			}
			boolean isShowInExperlor = false;
			String strShowInExperlor = request.getParameter("isShowInExperlor");
			if (null != strShowInExperlor && strShowInExperlor.trim().equals("true")) {
				isShowInExperlor = true;
			}
			
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			InputStream is = null;
			int byteLength = 0;
			byte[] content=new byte[1024];
			while ((byteLength = is.read(content)) > 0) {
				baos.write(content,0,byteLength);				
			}
			is.close();

			// 设置参数
			response.reset();
			// MimeType
			String strContentTypeTemp = mimeType;
			if (null == mimeType) {
				strContentTypeTemp = "charset=" + charset;
			} else {
				strContentTypeTemp = mimeType + ";charset=" + charset;
			}
			
			String strContentTemp = null;
			if (isShowInExperlor) {
				strContentTemp = "attachment;";
			} else {
				strContentTemp = "inline;";
			}
			if (null != charset) {
				String strFileNameTemp = new String(fileName.getBytes(),
						"UTF-8");
				strContentTemp = strContentTemp + "filename=" + strFileNameTemp;
			} else {
				strContentTemp = strContentTemp + "filename=" + fileName;
			}
			response.setHeader("Content-Disposition", strContentTemp);
			response.setContentLength(baos.size());

			// 写到浏览器
			OutputStream os = response.getOutputStream();
			baos.flush();
			os.write(baos.toByteArray());
			baos.close();
			os.flush();
			os.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}
}
